﻿using ElectronicWMSA.Comm.ClassFiles;
using ElectronicWMSA.Comm.Forms.Message;
using NPOI.XSSF.UserModel;
using SYDZ.WMS.DBUtility;
using System;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using WMSABL;
using WMSADBUtility;

namespace ElectronicWMSA.List.Second
{
    public partial class UPS_Manage : Form
    {
        public UPS_Manage()
        {
            InitializeComponent();
        }

        #region 函数
        public void DBind()
        {
            string query = "select top (30)* from T_UPS_Excel_Manage order by Tracking_No asc";
            DataSet ds = DBHelper.Query(query);
            DGV.DataSource = ds.Tables[0];
        }

        private void UPS_Manage_Load(object sender, EventArgs e)
        {
            this.page1.PageCurrent = 1;
            this.page1.PageSize = 30;
            this.page1.Bind();
        }


        #endregion

        #region 按钮：导入Excel表格
        private void btnInport_Click(object sender, EventArgs e)
        {
            ImportWindos frm = new ImportWindos();
            frm.ShowDialog();
            this.page1.Bind();
        }
        #endregion

        #region 按钮：关闭界面
        private void linkLabelClose_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseTabPages();
        }

        private void linkLabellinkLabelCloseAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseAllTabPages();
        }

        private void linkLabelCloseElse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseTabPageElse();
        }

        #endregion

        #region 按钮：插入数据
        private void btnInsert_Click(object sender, EventArgs e)
        {
            UPS_Insert insert = new UPS_Insert();
            insert.ShowDialog();
            DBind();
        }
        #endregion

        #region 按钮：刷新
        private void bt_Fresh_Click(object sender, EventArgs e)
        {
            DBind();
        }
        #endregion

        #region 双击修改
        private void DGV_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {

            if (e.RowIndex == -1)
                return;
            if (DGV.RowCount > 0)
            {
                if (DGV.Rows[index].Cells["Mark"].Value.ToString() == "1")
                { MessageClass.error("你所选行数据的订单号已经出库，不能进行修改操作"); }
                else
                {
                    int rindex = e.RowIndex;

                    string nid = DGV.Rows[rindex].Cells["nid"].Value.ToString();
                    string tracking_no = DGV.Rows[rindex].Cells["Tracking_No"].Value.ToString();
                    string model_no = DGV.Rows[rindex].Cells["Model_No"].Value.ToString();
                    string serial_no = DGV.Rows[rindex].Cells["Serial_No"].Value.ToString();
                    string city = DGV.Rows[rindex].Cells["City"].Value.ToString();


                    UPS_Change change = new UPS_Change(nid, tracking_no, model_no, serial_no, city);
                    change.ShowDialog();

                    DBind();
                }

            }
        }
        #endregion

        #region 按钮：删除
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (key == 0) { MessageClass.error("请选择行数据！"); return; }
            if (DGV.Rows[index].Cells["Mark"].Value.ToString() == "1")
            { MessageClass.error("你所选行数据的订单号已经出库，不能进行删除操作"); }
            else
            {
                if (MessageClass.enquire("是否要删除这条数据？\n"
                    + DGV.Rows[index].Cells["Tracking_No"].Value.ToString() + ","
                    + DGV.Rows[index].Cells["Model_No"].Value.ToString() + ","
                    + DGV.Rows[index].Cells["Serial_No"].Value.ToString() + ","
                    + DGV.Rows[index].Cells["City"].Value.ToString()) == DialogResult.OK)
                {
                    string query = "delete from [T_UPS_Excel_Manage] where nid = " + key + "";
                    int result = DBHelper.ExecuteSql(query);

                    if (result > 0)
                    {
                        MessageClass.right("数据删除成功");
                        SystemVariable.AddLogInfo("数据删除", "操作员：【" + SystemVariable.Login_Name + "】进行了删除操作");
                        DBind();
                        key = 0;
                    }
                }
            }
        }
        #endregion

        #region 按钮：同步数据
        private void bt_Synchrodata_Click(object sender, EventArgs e)
        {
            if (MessageClass.enquire("请确定是否要同步数据？") == DialogResult.OK)
            {
                SystemLoadCartoon();
                SynchrodataFirstTable();
                SynchrodataSecondTable();
                CheckStuteA();
                CheckStuteB();
                DBind();
                CartoonClose();
                MessageBox.Show("修改成功");
            }
        }

        /// <summary>
        /// 同步T_Stock表
        /// </summary>
        public void SynchrodataFirstTable()
        {
            //===============================================================
            string query = "update T_Stock set T_Stock.BK10 = T_UPS_Excel_Manage.City " +
                "from T_Stock JOIN T_UPS_Excel_Manage " +
            "on T_Stock.Product_Model = T_UPS_Excel_Manage.Model_No " +
            "and REPLACE(T_Stock.Serial_Number, '%','') = T_UPS_Excel_Manage.Serial_No " +
            "and (T_Stock.BK10 is null or T_Stock.BK10 = '') " +
            "and T_Stock.BK08 is not null " +
            "and T_UPS_Excel_Manage.Create_Time >= '"+ DateTime.Now.AddDays(-30) +  "' "+
            "and T_Stock.Create_Time >= '" + DateTime.Now.AddDays(-90) + "' " +
            " ";
            DBHelper.Query(query);
            //===============================================================
        }

        /// <summary>
        /// 同步T_PickStockPrepare表
        /// </summary>
        public void SynchrodataSecondTable()
        {
            //===============================================
            string query = "update T_PickStockPrepare set T_PickStockPrepare.BK10 = T_UPS_Excel_Manage.City " +
                "from T_PickStockPrepare JOIN T_UPS_Excel_Manage " +
            "on T_PickStockPrepare.Product_Model = T_UPS_Excel_Manage.Model_No " +
            "and REPLACE(T_PickStockPrepare.Serial_Number, '%','') = T_UPS_Excel_Manage.Serial_No " +
            "and (T_PickStockPrepare.BK10 is null or T_PickStockPrepare.BK10 = '') " +
            "and T_PickStockPrepare.BK08 is not null " +
            "and T_UPS_Excel_Manage.Create_Time >= '" + DateTime.Now.AddDays(-30) + "' " +
            "and T_PickStockPrepare.Update_Time >= '" + DateTime.Now.AddDays(-90) + "' " +
            " ";
            DBHelper.Query(query);
            //===============================================
        }
        #endregion

        #region 按钮：批量删除数据
        private void bt_Batch_Delete_Data_Click(object sender, EventArgs e)
        {
            UPS_Delete delete = new UPS_Delete();
            delete.ShowDialog();
            DBind();
        }
        #endregion

        int key = 0;
        int index = 0;
        /// <summary>
        /// 选中行内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DGV_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;
            //防止选中第一行报错
            if (DGV.RowCount > 0)
            {
                int rindex = e.RowIndex;

                index = rindex;

                key = Convert.ToInt32(DGV.Rows[rindex].Cells["nid"].Value.ToString());
            }
        }

        private string strWhere = "";
        #region 按钮：查询
        private void bt_Serarch_Click(object sender, EventArgs e)
        {

            if (!SystemVariable.VaildationPermission("查询")) return;
            strWhere = "1=1";
            //strWhere += " Create_Time BETWEEN '" + statTime + "'  AND '" + EndTime + "'";

            if (this.tb_Tracking_No.Text.Trim() != "")
                strWhere += " AND Tracking_No='" + this.tb_Tracking_No.Text.Trim() + "' ";
            if (this.tb_Model_No.Text.Trim() != "")
                strWhere += " AND Model_No='" + this.tb_Model_No.Text.Trim() + "' ";
            if (this.tb_Serial_No.Text.Trim() != "")
                strWhere += " AND Serial_No='" + this.tb_Serial_No.Text.Trim() + "' ";
            if (this.tb_Mark.Text.Trim() != "")
                strWhere += " AND Mark ='" + this.tb_Mark.Text.Trim() + "' ";
            if (this.tb_City.Text.Trim() != "")
                strWhere += " AND City='" + this.tb_City.Text.Trim() + "' ";
            if (this.dtpTimeStart.Checked)
            {
                strWhere += "  AND  Create_Time >= '" + dtpTimeStart.Text.Trim() + "'";

            }
            if (this.dtpTimeEnd.Checked)
            {
                strWhere += "  AND  Create_Time <= '" + dtpTimeEnd.Text.Trim() + "'";
            }

            this.page1.Bind();//
        }

        #endregion

        #region 初始化页面
        private int page1_EventPaging(Comm.Forms.MsControls.EventPagingArg e)
        {
            return DBindData();
        }
        private int DBindData()
        {
            Comm.Forms.MsControls.PageData pageData = new Comm.Forms.MsControls.PageData();
            pageData.TableName = "T_UPS_Excel_Manage";
            pageData.PrimaryKey = "nid";
            pageData.OrderStr = "nid";
            pageData.PageIndex = this.page1.PageCurrent;
            pageData.PageSize = this.page1.PageSize;
            pageData.QueryCondition = strWhere;
            pageData.QueryFieldName = "*";

            this.page1.bindingSource.DataSource = pageData.QueryDataTable().Tables[0];
            this.page1.bindingNavigator.BindingSource = page1.bindingSource;
            this.DGV.AutoGenerateColumns = false;
            this.DGV.DataSource = this.page1.bindingSource;
            this.DGV.ClearSelection();
            this.DGV.CurrentCell = null;
            return pageData.TotalCount;
        }
        #endregion

        private void DGV_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            SolidBrush b = new SolidBrush(DGV.RowHeadersDefaultCellStyle.ForeColor);
            e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), DGV.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
        }

        #region 按钮：导出表格
        private void bt_Output_Click(object sender, EventArgs e)
        {
            ExportExcel();
        }
        private void ExportExcel()
        {
            try
            {
                if (DGV.Rows.Count == 0)
                {
                    MessageClass.error("无数据,请确认!"); return;
                }
                string sql = "select [Tracking_No],[Model_No],[Serial_No],[City],[Create_Time] from T_UPS_Excel_Manage order by Tracking_No asc";
                if (MessageClass.enquire("是否要导出表中数据？") == DialogResult.OK)
                {
                    XSSFWorkbook workbook = new XSSFWorkbook();
                    WaitinglodingFrm wf = new WaitinglodingFrm((obj, args) =>
                    {
                        Thread.Sleep(100);
                        workbook = Export(sql);
                    }, 180);
                    wf.ShowDialog(this);

                    if (workbook != null)
                    {
                        SaveFileDialog dlg = new SaveFileDialog();
                        dlg.Filter = "Execl files (*.xlsx)|*.xlsx";
                        dlg.FileName = DateTime.Now.ToString("yyyyMMddHHmmss");
                        dlg.RestoreDirectory = true;
                        dlg.CreatePrompt = true;
                        dlg.Title = "保存为Excel文件";
                        if (dlg.ShowDialog() == DialogResult.OK)
                        {
                            using (FileStream fs = File.OpenWrite(dlg.FileName))
                            {
                                if (dlg.FileName != "")
                                {
                                    WaitinglodingFrm wf2 = new WaitinglodingFrm((obj, args) =>
                                    {
                                        Thread.Sleep(100);
                                        workbook.Write(fs);
                                    }, 1800);
                                    wf2.ShowDialog(this);
                                    fs.Close();
                                    MessageClass.right("导出成功！");
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageClass.error("导出失败！");
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLog.ErrorLogInfo("//////////////////////////////////  " + ex.Message.ToString());
                MessageClass.error("数据异常!");
            }
        }
        private XSSFWorkbook Export(string sql)
        {
            XSSFWorkbook workbook = new XSSFWorkbook();
            try
            {
                System.Data.DataTable _dtInfo = DBHelper.GetDataSet(sql).Tables[0];
                if (_dtInfo.Rows.Count > 0)
                {
                    workbook = ExcelUtil.DataTableExport(_dtInfo);
                }
                else
                {
                    MessageClass.error("无数据！");
                }
            }
            catch (Exception ex)
            {
                ErrorLog.ErrorLogInfo("////////////////////// " + ex.Message.ToString());
            }
            return workbook;

        }
        #endregion

        #region 按钮：导出数据
        private void bt_OutPut_Page_Click(object sender, EventArgs e)
        {
            if (DGV.Rows.Count > 0)
            {
                ExcelUtil.ExportDataGridViewToExcel(DGV);
            }
            else
            {
                MessageClass.error("无数据，请确认！");
            }
        }
        #endregion

        #region 检查订单是否出库
        /// <summary>
        /// 检查订单是否出库
        /// </summary>
        public void CheckStuteA()
        {


            string query = "update T_UPS_Excel_Manage set Mark = 1 " +
                "from T_Stock JOIN T_UPS_Excel_Manage " +
                "on T_Stock.Product_Model = T_UPS_Excel_Manage.Model_No " +
                "and REPLACE(T_Stock.Serial_Number, '%','') = T_UPS_Excel_Manage.Serial_No " +
                "and (T_Stock.BK10 is null or T_Stock.BK10 = '')" +
                "and T_Stock.BK08 is not null";
            DBHelper.Query(query);




            string query3 = "update T_UPS_Excel_Manage set Mark = 2" +
                "from T_Stock JOIN T_UPS_Excel_Manage " +
                "on T_Stock.Product_Model = T_UPS_Excel_Manage.Model_No " +
                "and REPLACE(T_Stock.Serial_Number, '%','') = T_UPS_Excel_Manage.Serial_No " +
                "and (T_Stock.BK10 is null or T_Stock.BK10 = '')";
            DBHelper.Query(query3);
        }

        public void CheckStuteB()
        {

            //=====================================================

            string query2 = "update T_UPS_Excel_Manage set Mark = 1 " +
                            "from T_PickStockPrepare JOIN T_UPS_Excel_Manage " +
                            "on T_PickStockPrepare.Product_Model = T_UPS_Excel_Manage.Model_No " +
                            "and REPLACE(T_PickStockPrepare.Serial_Number, '%','') = T_UPS_Excel_Manage.Serial_No " +
                            "and (T_PickStockPrepare.BK10 is null or T_PickStockPrepare.BK10 = '')" +
                            "and T_PickStockPrepare.BK08 is not null ";
            DBHelper.Query(query2);



            string query1 = "update T_UPS_Excel_Manage set Mark = 2  " +
                            "from T_PickStockPrepare JOIN T_UPS_Excel_Manage " +
                            "on T_PickStockPrepare.Product_Model = T_UPS_Excel_Manage.Model_No " +
                            "and REPLACE(T_PickStockPrepare.Serial_Number, '%','') = T_UPS_Excel_Manage.Serial_No " +
                            "and (T_PickStockPrepare.BK10 is null or T_PickStockPrepare.BK10 = '')";
            DBHelper.Query(query1);
            //=====================================================

        }
        #endregion

        #region 提示
        private void bt_Synchrodata_MouseHover(object sender, EventArgs e)
        {
            // 创建the ToolTip 
            ToolTip toolTip1 = new ToolTip();

            // 设置显示样式
            toolTip1.AutoPopDelay = 50000;//提示信息的可见时间
            toolTip1.InitialDelay = 500;//事件触发多久后出现提示
            toolTip1.ReshowDelay = 500;//指针从一个控件移向另一个控件时，经过多久才会显示下一个提示框
            toolTip1.ShowAlways = true;//是否显示提示框

            //  设置伴随的对象.
            toolTip1.SetToolTip(this.bt_Synchrodata, "同步订单号对应的城市信息，同时获得订单号的出入库状态");//设置提示按钮和提示内容

        }
        #endregion

        #region 加载动画
        private Form cartoonForm = new Form();

        private void SystemLoadCartoon()
        {
            Thread LoadCartoon = new Thread(delegate ()
            {
                PictureBox pb = new PictureBox();
                //加载图片
                Bitmap image = Properties.Resources.Waiting;
                pb.Image = image;
                //设置PictureBox大小
                pb.Width = pb.Image.Width;
                pb.Height = pb.Image.Height;
                pb.SizeMode = PictureBoxSizeMode.AutoSize;
                pb.Anchor = AnchorStyles.None;
                //设置窗口大小
                cartoonForm.FormBorderStyle = FormBorderStyle.None;
                cartoonForm.Width = pb.Image.Width;
                cartoonForm.Height = pb.Image.Width;
                //将PictureBox添加到Form里
                cartoonForm.Controls.Add(pb);
                //不显示Form的操作按钮，防止提前关闭窗口导致后面的invok方法报错
                cartoonForm.ControlBox = false;
                //显示窗口
                cartoonForm.StartPosition = FormStartPosition.CenterScreen;
                cartoonForm.ShowDialog();
            });
            LoadCartoon.Start();
        }
        private void CartoonClose()
        {


            //关闭加载动画
            cartoonForm.Invoke(new Action(() =>
            {
                cartoonForm.Close();
            }));
        }

        #endregion

        private void ShowExcel_Click(object sender, EventArgs e)
        {
            ShowExcel se = new ShowExcel();
            se.ShowDialog();
        }

        private void Instruction_Click(object sender, EventArgs e)
        {
            Instruction_Manual ins = new Instruction_Manual();
            ins.ShowDialog();
        }

        private void insertDatas_Click(object sender, EventArgs e)
        {
            UPS_Insert ui = new UPS_Insert();
            ui.ShowDialog();
        }
    }
}
